<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称">
        <span>{{ spu.spuName }}</span>
      </el-form-item>

      <el-form-item label="SKU名称">
        <el-input placeholder="SKU名称" v-model="skuForm.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格">
        <el-input
          placeholder="价格"
          type="number"
          v-model="skuForm.price"
        ></el-input>
      </el-form-item>
      <el-form-item label="重量">
        <el-input
          type="number"
          placeholder="重量"
          v-model="skuForm.weight"
        ></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input
          type="textarea"
          rows="4"
          placeholder="规格描述"
          v-model="skuForm.skuDesc"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form :inline="true" label-width="100px">
          <el-form-item
            :label="attr.attrName"
            v-for="attr in attrsList"
            :key="attr.id"
          >
            <!-- 这份数据暂时咱们先存到attr(平台属性)  收集平台属性id和属性值id-->
            <el-select placeholder="请选择" v-model="attr.AttrIdValueId">
              <el-option
                :label="attrValue.valueName"
                :value="`${attr.id}:${attrValue.id}`"
                v-for="attrValue in attr.attrValueList"
                :key="attrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form :inline="true" label-width="100px">
          <el-form-item
            :label="saleAttr.saleAttrName"
            v-for="saleAttr in spuSaleAttrList"
            :key="saleAttr.id"
          >
            <!-- 这份数据暂时咱们先存到saleAttr(销售属性) -->
            <el-select
              placeholder="请选择"
              v-model="saleAttr.saleAttrIdValueId"
            >
              <!-- 指定每一个value值是 销售属性id+销售属性值id -->
              <el-option
                :label="saleAttrValue.saleAttrValueName"
                v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                :key="saleAttrValue.id"
                :value="`${saleAttr.id}:${saleAttrValue.id}`"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片列表">
        <!-- @selection-change="handleSelectionChange" 选中变化时执行的回调函数 -->
        <el-table
          border
          @selection-change="handleSelectionChange"
          :data="spuImageList"
        >
          <el-table-column width="55" type="selection"></el-table-column>
          <el-table-column label="图片">
            <template v-slot="{ row, $index }">
              <el-image
                style="width: 100px; height: 80px"
                :src="row.imgUrl"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-button
                type="primary"
                @click="changeDefault(row, spuImageList)"
                v-if="row.isDefault === '0'"
                >设为默认</el-button
              >
              <el-tag type="success" v-else>默认</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="small"
          style="margin-right: 10px"
          @click="save"
          >保存</el-button
        >
        <el-button size="small" @click="cancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import attrApi from "@/api/attr";
import skuApi from "@/api/sku";
import { mapState } from "vuex";
export default {
  name: "SkuForm",
  props: ["spu"],
  computed: {
    ...mapState("category", ["category1Id", "category2Id", "category3Id"]),
  },
  data() {
    return {
      attrsList: [],
      spuSaleAttrList: [],
      spuImageList: [],
      skuImageList: [], //要收集的sku图片列表
      skuForm: {
        // v-model
        price: "",
        skuName: "",
        skuDesc: "",
        weight: "",
        // 从传递进来的spu中获取
        spuId: "",
        tmId: "",
        category3Id: "",
        // 得通过咱们自己书写的逻辑获取
        skuDefaultImg: "",
        skuImageList: [],
        skuAttrValueList: [],
        skuSaleAttrValueList: [],
      },
    };
  },
  methods: {
    // 专门用来发送添加sku所需要的三个请求
    async initAddSkuData() {
      try {
        // 获取所有的平台属性列表
        const p1 = attrApi.getAttrsList(
          this.category1Id,
          this.category2Id,
          this.category3Id
        );
        // 获取spu的销售属性列表
        const p2 = skuApi.getSpuSaleAttrList(this.spu.id);
        // 获取spu的图片列表
        const p3 = skuApi.getSpuImageList(this.spu.id);
        const res = await Promise.all([p1, p2, p3]);
        this.attrsList = res[0].data;
        this.spuSaleAttrList = res[1].data;
        this.spuImageList = res[2].data;
        this.spuImageList.forEach((item) => {
          this.$set(item, "isDefault", "0");
        });
      } catch (error) {
        this.$message({
          type: "error",
          message: "初始化数据失败",
        });
      }
    },
    // 选中状态变化时执行的回调
    handleSelectionChange(val) {
      // val就是选中的图片列表
      // 拿到选中的图片列表 给一个新的数组 如果直接对spuImageList赋值 不行 因为数据结构不同 一张图片都显示不了了
      this.skuImageList = val;
    },
    changeDefault(row, spuImageList) {
      // 排它完成默认图片的选择
      spuImageList.forEach((item) => {
        item.isDefault = "0";
      });
      row.isDefault = "1";
      // 收集默认图片的地址
      this.skuForm.skuDefaultImg = row.imgUrl;
    },
    // 保存
    async save() {
      // 1.获取参数
      let skuParams = this.skuForm;
      // 2.整理参数
      skuParams.spuId = this.spu.id;
      skuParams.tmId = this.spu.tmId;
      skuParams.category3Id = this.spu.category3Id;
      // 处理skuImageList
      skuParams.skuImageList = this.skuImageList.map((item) => {
        return {
          imgName: item.imgName,
          imgUrl: item.imgUrl,
          spuImgId: item.id, //item是某一个sku的图片  是从spu图片中进行选择
          isDefault: item.isDefault,
        };
      });
      // 平台属性值列表
      skuParams.skuAttrValueList = this.attrsList.reduce((prev, item) => {
        if (item.AttrIdValueId) {
          //说明咱们之前在平台属性中选中过这个属性值 属性id:属性值id
          let [attrId, valueId] = item.AttrIdValueId.split(":");
          let obj = { attrId, valueId }; //组成一个sku的平台属性值对象
          prev.push(obj);
        }
        return prev;
      }, []);
      // 销售属性值列表
      skuParams.skuSaleAttrValueList = this.spuSaleAttrList.reduce(
        (prev, item) => {
          if (item.saleAttrIdValueId) {
            //说明咱们之前在销售属性中选中过这个属性值 销售属性id:销售属性值id
            let [saleAttrId, saleAttrValueId] =
              item.saleAttrIdValueId.split(":");
            let obj = { saleAttrId, saleAttrValueId }; //组成一个sku的销售属性值对象
            prev.push(obj);
          }
          return prev;
        },
        []
      );
      try {
        await skuApi.saveSkuInfo(skuParams);
        this.$message({
          type: "success",
          message: "添加sku成功",
        });
        this.$emit("setShowState", 1);
      } catch (error) {
        this.$message({
          type: "errorerror",
          message: "添加sku失败",
        });
      }
    },
    // 取消
    cancle() {
      this.$emit("setShowState", 1);
    },
  },
  mounted() {
    this.initAddSkuData();
  },
};
</script>

<style lang="scss" scoped></style>
